package com.rightsidetech.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.mall.dto.request.TypePageReq;
import com.rightsidetech.mall.dto.request.TypeReq;
import com.rightsidetech.mall.dto.request.TypeUpReq;
import com.rightsidetech.mall.dto.response.TypePageResp;
import com.rightsidetech.mall.entity.MallType;
import com.rightsidetech.mall.mapper.MallBaseInfoMapper;
import com.rightsidetech.mall.mapper.MallCommodityMapper;
import com.rightsidetech.mall.mapper.MallTypeMapper;
import com.rightsidetech.mall.service.MallTypeService;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("mallTypeService")
public class MallTypeServiceImpl implements MallTypeService {

    @Resource
    private MallTypeMapper mallTypeMapper;
    @Resource
    private MallBaseInfoMapper mallBaseInfoMapper;

    @Override
    public ResponseData save(TypeReq req, String createrName, Long createrId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long count = mallTypeMapper.selectCountByTypeName(req.getTypeName());
        if(count > 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"分类名称已存在不可重复添加");
        }
        MallType type = new MallType();
        type.setCreaterName(createrName);
        type.setCreaterId(createrId);
        type.setCreatedAt(new Date());
        type.setTypeName(req.getTypeName());
        type.setIsDeleted((byte)0);
        if(req.getId() != null){
            return saveChildType(req.getId(),type);
        }
        type.setGrade((byte)1);
        type.setParentId(0L);
        if (mallTypeMapper.insertSelective(type) <= 0) {
            return ResponseData.fail("添加失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    private ResponseData saveChildType(Long id, MallType type) {
        MallType mallType = mallTypeMapper.selectByPrimaryKey(id);
        if(ObjectUtil.isEmpty(mallType) || mallType.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"上级分类不存在");
        }
        type.setParentId(id);
        type.setGrade((byte) (mallType.getGrade() + 1));
        if (mallTypeMapper.insertSelective(type) <= 0) {
            return ResponseData.fail("添加失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData update(TypeUpReq req, String updaterName, Long updaterId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallType type = mallTypeMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(type) || type.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"修改的数据不存在");
        }
        if(!req.getTypeName().equals(type.getTypeName())){
            Long count = mallTypeMapper.selectCountByTypeName(req.getTypeName());
            if(count > 0){
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"分类名称已存在不可重复添加");
            }
        }
        type = new MallType();
        type.setUpdatedAt(new Date());
        type.setUpdaterId(updaterId);
        type.setTypeName(req.getTypeName());
        type.setUpdaterName(updaterName);
        type.setId(req.getId());
        if (mallTypeMapper.updateByPrimaryKeySelective(type) <= 0) {
            return ResponseData.fail("更新失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData isDelete(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        MallType mallType = mallTypeMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(mallType) || mallType.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"要删除数据不存在");
        }
        Long count = mallTypeMapper.selectCountByParentId(req.getId());
        if(count > 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此分类有子分类不允许删除");
        }
        Long infoCount = mallBaseInfoMapper.selectCountByTypeId(req.getId());
        if(infoCount > 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"此分类有基础商品使用,不允许删除");
        }
        MallType record = new MallType();
        record.setId(req.getId());
        record.setIsDeleted((byte)1);
        if (mallTypeMapper.updateByPrimaryKeySelective(record) <= 0) {
            return ResponseData.fail("删除失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<PageInfo<TypePageResp>> page(TypePageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<TypePageResp> result = mallTypeMapper.selectPageList(req);
        for (TypePageResp resp : result) {
            if(resp.getCount() <= 0){
                resp.setChildren(null);
                resp.set_loading(null);
            }
        }
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData<List<TypePageResp>> getChildList(Long id) {
        if(null == id || id <= 0){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"id不可为空不能小于0");
        }
        List<TypePageResp> result = mallTypeMapper.selectChildList(id);
        for (TypePageResp resp : result) {
            if(resp.getCount() <= 0){
                resp.setChildren(null);
                resp.set_loading(null);
            }
        }
        return ResponseData.success(result);
    }

    @Override
    public ResponseData<List<TypePageResp>> getAll() {
        List<MallType> typeList = mallTypeMapper.selectAll();
        if(CollUtil.isEmpty(typeList)){
            return ResponseData.success();
        }
        List<TypePageResp> result = new ArrayList<>();
        typeList.stream().filter(type -> type.getParentId() == 0).forEach(type -> {
            TypePageResp resp = new TypePageResp();
            resp.setId(type.getId());
            resp.setTypeName(type.getTypeName());
            resp.setCreatedAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(type.getCreatedAt()));
            resp.setGrade(type.getGrade());
            resp.setCreaterName(type.getCreaterName());
            result.add(resp);
        });
        recursion(result,typeList);
        return ResponseData.success(result);
    }

    private void recursion(List<TypePageResp> result, List<MallType> typeList) {
        if(CollUtil.isEmpty(result)){
            return;
        }
        for (TypePageResp resp : result) {
            List<TypePageResp> children = new ArrayList<>();
            typeList.stream().filter(type -> resp.getId().equals(type.getParentId())).forEach(type -> {
                TypePageResp resp1 = new TypePageResp();
                resp1.setId(type.getId());
                resp1.setTypeName(type.getTypeName());
                resp1.setCreatedAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(type.getCreatedAt()));
                resp1.setGrade(type.getGrade());
                resp1.setCreaterName(type.getCreaterName());
                children.add(resp1);
                resp.setChildren(children);
            });
            if (CollUtil.isNotEmpty(children)) {
                recursion(children, typeList);
            }
        }
    }

    @Override
    public ResponseData<List<TypePageResp>> getAppTypeList(Long agentId) {
        List<TypePageResp> result = mallTypeMapper.selectAppTypeList(agentId);
        return ResponseData.success(result);
    }
}
